<script setup lang="ts">
import type { ITableCol, ITableDataSet, ITableRow } from '@/types'
import { GcSpreadSheets } from '@grapecity-software/spread-sheets-vue'
import * as GC from '@grapecity/spread-sheets'
import { onBeforeMount, onMounted, ref, watch } from 'vue'
import HeaderCheckBoxCellType from './HeaderCheckBoxCellType'
import '@grapecity/spread-sheets/styles/gc.spread.sheets.excel2013lightGray.css'

interface IProps {
  mainData?: ITableDataSet
  remark?: number
  spaceBtnShow?: boolean
}
// Props
const props = withDefaults(defineProps<IProps>(), {
  remark: 0,
  mainData: () => ({} as ITableDataSet),
  spaceBtnShow: true,
})
// 找不到17.0.2版本的中文包
// import "@grapecity/spread-sheets/js/zh.js";
// import "@grapecity
// GC.Spread.Common.CultureManager.culture('zh-cn');

const GCsheets = GC.Spread.Sheets
// 类型定义
type SpreadWorkbook = GC.Spread.Sheets.Workbook
type SpreadWorksheet = GC.Spread.Sheets.Worksheet
type SpreadStyle = GC.Spread.Sheets.Style
type SpreadLineBorder = GC.Spread.Sheets.LineBorder
// type SpreadCell = GC.Spread.Sheets.Cell;
// type SpreadRange = GC.Spread.Sheets.Range
type SpreadComboBox = GC.Spread.Sheets.CellTypes.ComboBox
type SpreadCheckBox = GC.Spread.Sheets.CellTypes.CheckBox

const spreadRef = ref(null)
const spreadWorkbook = ref<SpreadWorkbook | null>(null)
const sheet = ref<SpreadWorksheet | null>(null)
onBeforeMount(() => { })
onMounted(() => {
})
function workbookInitialized(workbook: SpreadWorkbook) {
  spreadWorkbook.value = workbook
  sheet.value = spreadWorkbook.value.getActiveSheet()
  setOptions()
}

// 设置表格选项
function setOptions() {
  if (!sheet.value)
    return
  const activeSheet = sheet.value

  // 基本选项
  activeSheet.autoGenerateColumns = true
  activeSheet.options.allowCellOverflow = true

  // 默认尺寸
  activeSheet.defaults.rowHeight = 23
  activeSheet.defaults.colWidth = 100
  activeSheet.defaults.colHeaderRowHeight = 23
  activeSheet.defaults.rowHeaderColWidth = 60

  // 保护选项
  activeSheet.options.isProtected = true
  activeSheet.options.protectionOptions = {
    allowResizeColumns: true,
    allowInsertRows: true,
    allowDeleteRows: true,
    allowSelectLockedCells: true,
    allowSelectUnlockedCells: true,
    allowDeleteColumns: true,
    allowInsertColumns: true,
    allowDragInsertRows: true,
    allowDragInsertColumns: true,
    allowSort: true,
    allowFilter: true,
  }

  // activeSheet.options.allowUserDragDrop = true;
  // activeSheet.options.tabStripVisible = false;

  // 默认样式
  const defaultStyle = new GC.Spread.Sheets.Style() as SpreadStyle
  defaultStyle.font = '12px basefontRegular, Roboto, Helvetica, Arial, sans-serif'
  defaultStyle.hAlign = GC.Spread.Sheets.HorizontalAlign.left
  defaultStyle.vAlign = GC.Spread.Sheets.VerticalAlign.center

  // 边框设置
  const borderStyle = GC.Spread.Sheets.LineStyle.thin
  const borderColor = 'gray'
  defaultStyle.borderLeft = new GC.Spread.Sheets.LineBorder(borderColor, borderStyle) as SpreadLineBorder
  defaultStyle.borderTop = new GC.Spread.Sheets.LineBorder(borderColor, borderStyle) as SpreadLineBorder
  defaultStyle.borderRight = new GC.Spread.Sheets.LineBorder(borderColor, borderStyle) as SpreadLineBorder
  defaultStyle.borderBottom = new GC.Spread.Sheets.LineBorder(borderColor, borderStyle) as SpreadLineBorder

  defaultStyle.showEllipsis = true
  activeSheet.setDefaultStyle(defaultStyle, GC.Spread.Sheets.SheetArea.viewport)
}

function setSpreadData() {
  if (!spreadWorkbook.value || !sheet.value)
    return
  spreadWorkbook.value.suspendPaint()
  const activeSheet = sheet.value
  const { tableColumns: columns, tableDatas: tableData } = props.mainData

  columns.forEach((col: ITableCol, colIndex: number) => {
    col.name = col.prop
    col.displayName = col.label
    col.width = typeof col.width === 'string' ? Number(col.width) : col.width
    if (col.prop === 'isChecked') {
      const cellType = new HeaderCheckBoxCellType()
      // 选框
      activeSheet.setCellType(0, 0, cellType, GCsheets.SheetArea.colHeader)
      col.cellType = new GC.Spread.Sheets.CellTypes.CheckBox()
    }
    else if (
      col.ControlType === 'comboboxMultiple'
      || col.ControlType === 'combobox'
    ) {
      tableData.forEach((item: ITableRow, index: number) => {
        // item.RowNumber过滤统计行
        if (col.DataSourceID && col.DataSourceName && item.RowNumber) {
          const newData = item[col.DataSourceName] || col.Items || []// 优先获取数据行返回的数据源，没有则获取表头统一配置的数据源，都没有则空数组
          // 获取要绑定下拉菜单的单元格对象
          const cell = activeSheet.getCell(index, colIndex)
          // 创建下拉菜单单元格类型，并设置其选项数据
          const comboBox = new GC.Spread.Sheets.CellTypes.ComboBox() as SpreadComboBox
          comboBox.editorValueType(
            GC.Spread.Sheets.CellTypes.EditorValueType.value,
          )
          comboBox.editable(false)
          // 获取下拉菜单的选项数据
          comboBox.items(newData)
          comboBox.itemHeight(24)
          // 将下拉菜单单元格类型绑定到指定的单元格中
          cell?.cellType(comboBox)
        }
        // 没有item.RowNumber 的行是统计行
        else if (!item.RowNumber) {
          // 把表格数据统计行 下拉菜单获取的有数据的列 数据置空
          // props.mainData.tableDatas[index][col.prop] = null
          activeSheet.getRange(index, -1, 1, 1).locked(false)
        }
      })
    }
    else if (col.ControlType === 'checkbox') {
      const cellType = new GC.Spread.Sheets.CellTypes.CheckBox() as SpreadCheckBox
      cellType.caption('')
      cellType.textTrue('')
      cellType.textFalse('')
      cellType.textIndeterminate('')
      // cellType.textAlign(GC.Spread.Sheets.CellTypes.CheckBoxTextAlign.center);
      cellType.isThreeState(false)
      activeSheet.getCell(-1, colIndex).cellType(cellType)
    }
    else if (col.DataType === 'datetime' && col.isEdit) {
      const rangeCalendarStyle = new GC.Spread.Sheets.Style()
      rangeCalendarStyle.formatter = '@'
      rangeCalendarStyle.cellButtons = [
        {
          imageType: GC.Spread.Sheets.ButtonImageType.dropdown,
          command: 'openDateTimePicker',
          useButtonStyle: true,
        },
      ]
      rangeCalendarStyle.dropDowns = [
        {
          type: GC.Spread.Sheets.DropDownType.dateTimePicker,
          option: {
            showTime: false,
            startDay: GC.Spread.Sheets.CalendarStartDay.sunday,
          },
        },
      ]
      activeSheet.setStyle(-1, colIndex, rangeCalendarStyle)
    }
    else if (
      col.DataType === 'datetime'
      || col.DataType === 'varchar'
      || col.DataType === 'nvarchar'
    ) {
      col.formatter = '@'
    }

    // 设置可编辑列 字体颜色
    if (col.isEdit) {
      activeSheet.getCell(-1, colIndex).locked(false).foreColor('#2a06ecd9')
    }
  })
  activeSheet.setDataSource(tableData)
  activeSheet.bindColumns(columns as GC.Spread.Sheets.IColumn[])
  spreadWorkbook.value.resumePaint() // spread表格配置 优化 区间结束 设置
  spreadWorkbook.value.refresh()
}
watch(props.mainData.tableDatas, () => {
  console.warn('watch props.mainData.tableDatas')
  spreadWorkbook?.value?.refresh()
})
watch(props.mainData.tableColumns, (val) => {
  if (val && val.length) {
    setSpreadData()
  }
}, { immediate: true })
defineExpose({
  setSpreadData,
})
// 定义组件实例类型（可选但推荐）
export interface ISpreadExpose {
  setSpreadData: () => void
}
</script>

<template>
  <GcSpreadSheets
    ref="spreadRef" class="spreadsheets" :host-style="{ height: '100%', width: '100%' }"
    :tab-strip-visible="false" @workbook-initialized="workbookInitialized"
  />
</template>

<style scoped lang=""></style>
